package com.gitee.wsl.ext.okio

import okio.Buffer
import okio.EOFException
import kotlin.math.min

/**
 * Returns true if the [Buffer] contains human readable text. Uses a small sample
 * of code points to detect unicode control characters commonly used in binary file signatures.
 */
val Buffer.isProbablyPlainText
    get() = try {
        val prefix = Buffer()
        val byteCount = min(size, MAX_PREFIX_SIZE)
        copyTo(prefix, 0, byteCount)
        sequence { while (!prefix.exhausted()) yield(prefix.readUtf8CodePoint()) }
            .take(CODE_POINT_SIZE)
            .all { codePoint -> codePoint.isPlainTextChar() }
    } catch (_: EOFException) {
        false // Truncated UTF-8 sequence
    }

internal fun Int.isPlainTextChar() = this.toChar().run { isWhitespace() || isISOControl() }

